class Index {
    constructor() {
        this.userActions = document.querySelector('.user-actions');
        this.mainTitle = document.querySelector('.main-title');
        this.init();
    }

    init() {
        this.checkLoginStatus();
        this.bindEvents();
    }

    bindEvents() {
        // 绑定购买商品标题点击事件
        this.mainTitle.addEventListener('click', () => {
            this.handleBuyClick();
        });
    }

    // 处理购买点击
    handleBuyClick() {
        const token = localStorage.getItem('token');
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');

        if (!token || !userInfo) {
            // 未登录，跳转到登录页面
            alert('请先登录！');
            window.location.href = 'login.html';
        } else {
            // 已登录，跳转到商品列表页面
            window.location.href = 'goods-list.html';
        }
    }

    // 检查登录状态
    checkLoginStatus() {
        const token = localStorage.getItem('token');
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');

        if (token && userInfo) {
            // 已登录状态
            this.userActions.innerHTML = `
                <span>您好，${userInfo.nickname || userInfo.username}！</span>
                <a href="profile.html" class="login-btn">个人中心</a>
                <a href="javascript:void(0)" class="login-btn" onclick="window.indexPage.handleLogout()">退出登录</a>
            `;
        }
    }

    // 处理退出登录
    async handleLogout() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        
        try {
            const response = await fetch(`http://localhost:8888/users/logout/${userInfo.id}`, {
                headers: {
                    'authorization': localStorage.getItem('token')
                }
            });

            const data = await response.json();
            
            if (data.code === 1) {
                // 清除登录信息
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                
                alert('退出登录成功！');
                window.location.reload();
            } else {
                alert(data.message || '退出登录失败，请重试');
            }
        } catch (error) {
            alert('退出登录失败，请检查网络连接');
            console.error('退出登录错误：', error);
        }
    }
}

// 初始化首页功能
window.indexPage = new Index(); 